var express = require("express");
const jwt = require("jsonwebtoken");
const { query } = require("../public/javascripts/library/conn");

var router = express.Router();

// router.use((req, res, next) => {
//   // 从前端获取token;
//   let author = req.headers.authorization;

//   // 放过不需要验证的路由;
//   let url = ["/users/login"];
//   if (url.includes(req._parsedOriginalUrl.pathname)) {
//     return next();
//   }
//   console.log(author);
// });

//用户登录
/* GET users listing. */
router.get("/login", async function (req, res, next) {
  let username = req.query.username;
  let passwd = req.query.password;
  let sql = `select * from users where username="${username}" and password="${passwd}"`;
  let data = await query(sql);
  if (data.length == 0) {
    res.send({ success: 0, msg: "密码或用户名错误", token: "" });
  } else {
    let userinfo = req.query;
    let token = jwt.sign(userinfo, "PrivateKey", { expiresIn: 60 });
    res.send({ success: 1, msg: "登陆成功", token });
  }
});

module.exports = router;
